/**
 * 接口
 */
export default function DEMO() {
    //额外类型检查
    interface SquareConfig {
        color?: string;
        width?: number;
        [propName: string]: any;
    }

    function createSquare(config: SquareConfig): { color: string; area: number } {
        let newSquare = { color: "white", area: 100 };
        if (config.color) {
            newSquare.color = config.color;
        }
        if (config.width) {
            newSquare.area = config.width * config.width;
        }
        return newSquare;
    }

    let mySquare = createSquare({ colour: "red", width: 100 });


    //函数类型
    interface SearchFunc {
        (source: string, subString: string): boolean;
    }
    let mySearch: SearchFunc;
    mySearch = function (src: string, sub: string): boolean {
        let result = src.search(sub);
        return result > -1;
    }


    //类类型 实现接口
    // interface ClockInterface {
    //     currentTime: Date;
    //     setTime(d: Date);
    // }

    // class Clock implements ClockInterface {
    //     currentTime: Date;
    //     setTime(d: Date) {
    //         this.currentTime = d;
    //     }
    //     constructor(h: number, m: number) { }
    // }

    interface ClockConstructor {
        new(hour: number, minute: number): ClockInterface;
    }
    interface ClockInterface {
        tick();
    }

    function createClock(ctor: ClockConstructor, hour: number, minute: number): ClockInterface {
        return new ctor(hour, minute);
    }

    class DigitalClock implements ClockInterface {
        constructor(h: number, m: number) { }
        tick() {
            console.log("beep beep");
        }
    }
    class AnalogClock implements ClockInterface {
        constructor(h: number, m: number) { }
        tick() {
            console.log("tick tock");
        }
    }

    let digital = createClock(DigitalClock, 12, 17);
    let analog = createClock(AnalogClock, 7, 32);
    digital.tick();
    
    return (function () {
        document.getElementById('code').innerHTML = `
        /**
         * 接口
         */
        //额外类型检查
        interface SquareConfig {
            color?: string;
            width?: number;
            [propName: string]: any;
        }
    
        function createSquare(config: SquareConfig): { color: string; area: number } {
            let newSquare = { color: "white", area: 100 };
            if (config.color) {
                newSquare.color = config.color;
            }
            if (config.width) {
                newSquare.area = config.width * config.width;
            }
            return newSquare;
        }
    
        let mySquare = createSquare({ colour: "red", width: 100 });
        `
    })()
}
